<template>
  <el-drawer title="新增" :visible="visible" direction="rtl" :wrapperClosable="false"
             :close-on-press-escape="false" :show-close="true" @close="$emit('close')">
    <el-row style="height: calc(100% - 42px);">
      <ele-form
          v-model="formData"
          v-bind="$attrs"
          :requestFn="requestFn"
          @request-success="handleRequestSuccess"
          @request-error="handleRequestError"
          ref="ele-form"
          label-position="right">
        <div slot="form-btn"></div>
      </ele-form>
    </el-row>
    <el-row style="height: 42px;text-align: right;border-top: 1px solid #e4e7ed;padding-top: 10px;">
      <el-button size="small" type="primary" icon="el-icon-check" @click="addSave">保存</el-button>
      <el-button size="small" icon="el-icon-refresh-right" @click="resetForm">重置</el-button>
      <el-button size="small" type="danger" icon="el-icon-close" @click="$emit('close')">关闭</el-button>
    </el-row>
  </el-drawer>

</template>

<script>
import mixins from "../mixins/mixins";
import request from "../../../../../utils/request";

export default {
  name: "addFormDrawer",
  mixins: [mixins],
  props: {
    visible: Boolean,
    addUrl: String,
    dependId:[Object]
  },
  data() {
    return {
      formData: {}
    }
  },
  methods: {

    resetForm() {
      this.getEleForm().resetForm();
    },
    addSave() {
      this.getEleForm().handleSubmitForm();
    },
    //
    requestFn(data) {
      if (this.dependId){
        data = {...this.dependId,...data}
      }
      // 伪代码
      return new Promise(async (resolve, reject) => {
        try {
          if (this.addUrl) {
            request({
              url: this.addUrl,
              method: 'post',
              data
            })
                .then(data => {
                  resolve()
                })
                .catch(error => {
                  reject(error)
                })
          } else {
            throw new Error("保存地址add_url未配置")
          }
        } catch (error) {
          this.$message.error(error.message)
        }
      })
    },
    // 成功后的进一步处理
    handleRequestSuccess() {
      this.$message.success('保存成功')
      this.$emit('saveSuccess')
    },
    // 失败后的进一步处理（内部已经有提示）
    handleRequestError() {

    },
  },
  watch: {
    visible(val) {
      if (val) {
        //初始化
      }
    }
  }
}
</script>

<style scoped>

</style>